﻿using System;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting;
using Microsoft.Linq.Expressions;
using System.Reflection;

namespace BTR.Calculation.ExpressionEngine.Excel.Runtime.Binding
{
	public class CellBinder : GetIndexBinder
	{
		public ExcelBinder Binder { get; private set; }
		public Expression Context { get; private set; }
		public SymbolId Symbol { get; private set; }

		public CellBinder( ExcelBinder binder, Expression context, SymbolId symbol )
		{
			this.Binder = binder;
			this.Context = context;
			this.Symbol = symbol;
		}

		public override DynamicMetaObject FallbackGetIndex( DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject errorSuggestion )
		{
			return new DynamicMetaObject(
				Expression.Property(
					Expression.Call(
						target.Expression,
						typeof( ICellContext ).GetMethod( "GetCell", BindingFlags.Instance | BindingFlags.Public ),
						Expression.Constant( Symbol ) ),
					"Value" ),
				BindingRestrictions.Empty );
		}

		public override object HashCookie
		{
			get { return this; }
		}
	}
}